import axios from "axios";
import { ElMessage } from "element-plus";

//创建一个axios实例
const service = axios.create({
  baseURL: "http://localhost:3000",
});

//对实例添加一个统一的返回拦截器
service.interceptors.response.use(
  (response) => {
    const { status, data, statusText } = response;
    if (status === 200) {
      return data;
    } else {
      ElMessage.error(statusText);
      return Promise.reject(statusText);
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);

//封装axios的请求消息发送
function request(option) {
  option.method = option.method || "get";
  if (option.method.toLowerCase() === "get") {
    option.params = option.data;
  }
  //调用axios，发送请求
  return service(option);
}

export default request;
